/**
 * 请求拦截
 * @param {Object} http
 */
import errorCode from "@/utils/errorCode";
import { http } from "uview-plus";
const requestInterceptors = (vm) => {
  http.interceptors.request.use(
    (config) => {
      // 可使用async await 做异步操作
      // 初始化请求拦截器时，会执行此方法，此时data为undefined，赋予默认{}
      config.data = config.data || {};
      if (uni.$sc.getToken()) {
        config.header.userjwttoken = uni.$sc.getToken();
      }
      return config;
    },
    (
      config // 可使用async await 做异步操作
    ) => Promise.reject(config)
  );
};
const responseInterceptors = (vm) => {
  /**
   * 响应拦截
   * @param {Object} http
   */
  http.interceptors.response.use(
    async (res) => {
      const code = res.data.code || 0;
      const msg = res.data.msg || errorCode[code] || errorCode["default"];
      if (code === 401) {
        uni.$sc
          .showConfirm("登录状态已过期，您可以继续留在该页面，或者重新登录?")
          .then((res) => {
            if (res.confirm) {
              // store.dispatch('LogOut').then(res => {
              //   uni.reLaunch({ url: '/pages/login' })
              // })
            }
          });
        return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
      } else if (code === 500) {
        uni.$sc.toast(msg);
        return Promise.reject("500");
      } else if (code != 1) {
        uni.$sc.toast(msg);
        return Promise.reject(code);
      }
      return Promise.resolve(res.data);
    },
    (err) => {
      let { message } = err;
      if (!message) {
        message = "系统发生未知错误";
      } else if (message === "Network Error") {
        message = "后端接口连接异常";
      } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
      } else if (message.includes("Request failed with status code")) {
        message = "系统接口" + message.substring(message.length - 3) + "异常";
      }
      uni.$sc.toast(message);
      return Promise.reject(err);
    }
  );
};

export { requestInterceptors, responseInterceptors };
